<?php
define( 'PERIOD', 60*60*12 ); // 12 hours
class backup {
  /**
   * backup directory
   * @var string
   */
  public static $dir = 'backup/';
  /**
   * tables to backup
   * @var string
   */
  public static $tables = 'clients config content pages program req users';
  /**
   * backup period in secounds
   * @var int
   */
  public static $period = PERIOD;
  /**
   * date and time of last backup
   * @return timestamp
   */
  public static function last() {
    foreach( scandir( self::$dir, 1 ) as $file ) {
      if ( $file === '.' || $file === '..' )
      continue;
      list( $time, $type ) = explode( '.', $file, 2 );
      if (is_numeric( $time ) && $type==='sql' )
      break;
    }
    return empty($time) ? 0 : $time+0;
  }
  /**
   * save dump
   * @return void
   */
  public static function dump( $force=false ) {
    if ( $force || ( time() - self::last() ) > self::$period ) {
      $file = getcwd().'/'.self::$dir.time().'.sql';
      file_put_contents( $file, mysql_dump(mysql_db) );
      //$command = "mysqldump --opt -h ".mysql_host." -u ".mysql_login." --password=".mysql_pwd." ".mysql_db." ".self::$tables."  > $file";
      //system($command);
    }
  }
  /**
   * Leaves specified number of backup files
   * @param $num
   * @return unknown_type
   */
  public static function leave($num) {
    $i = 0;
    foreach( scandir( self::$dir, 1 ) as $file ) {
      if ( $file === '.' || $file === '..' )
      continue;
      list( $time, $type ) = explode( '.', $file, 2 );
      if (is_numeric( $time ) && $type==='sql' && $i<$num ) {
        ++$i;
      } else {
        unlink( self::$dir.$file );
      }
    }
  }
}

define ( 'lnbr', "\n" );
function mysql_dump($database) {
  $query = '';
  $tables = @mysql_list_tables($database);
  while ($row = @mysql_fetch_row($tables)) { $table_list[] = $row[0]; }
  for ($i = 0; $i < @count($table_list); $i++) {
    $results = mysql_query('DESCRIBE ' . $database . '.' . $table_list[$i]);
    $query .= 'DROP TABLE IF EXISTS `' . $table_list[$i] . '`;' . lnbr;
    $query .= lnbr . 'CREATE TABLE `' . $table_list[$i] . '` (' . lnbr;
    $tmp = '';
    while ($row = @mysql_fetch_assoc($results)) {
      $query .= '`' . $row['Field'] . '` ' . $row['Type'];
      if ($row['Null'] != 'YES') { $query .= ' NOT NULL'; }
      if ($row['Default'] != '') { $query .= ' DEFAULT \'' . $row['Default'] . '\''; }
      if ($row['Extra']) { $query .= ' ' . strtoupper($row['Extra']); }
      if ($row['Key'] == 'PRI') { $tmp = 'primary key(' . $row['Field'] . ')'; }
      $query .= ','. lnbr;
    }
    $query .= $tmp . lnbr . ') ENGINE=MyISAM DEFAULT CHARSET=utf8;' . str_repeat(lnbr, 2);
    $results = mysql_query('SELECT * FROM ' . $table_list[$i]);
    while ($row = @mysql_fetch_assoc($results)) {
      $query .= 'INSERT INTO `' . $table_list[$i] .'` (`';
      $data = Array();
      while (list($key, $value) = @each($row)) { $data['keys'][] = $key; $data['values'][] = addslashes($value); }
      $query .= join($data['keys'], '`, `') . '`)' . lnbr . 'VALUES (\'' . join($data['values'], '\', \'') . '\');' . lnbr;
    }
    $query .= str_repeat(lnbr, 2);
  }
  return $query;
}


?>